package com.wenjie.plugin;

import android.app.Application;
import android.content.Context;
import android.os.Environment;

import com.pantum.lld.DeviceManager;
import com.wenjie.plugin.util.CLog;
import com.wenjie.plugin.util.ConfigurationUtil;
import com.wenjie.plugin.util.FileUtil;
import com.wenjie.plugin.util.Global;

import java.io.File;

import io.dcloud.feature.uniapp.UniAppHookProxy;

/**
 * 插件注册
 */
public class PrinterProxy implements UniAppHookProxy {

    private Global global;

    /**
     * 当前uni应用进程回调 仅触发一次 多进程不会触发
     */
    @Override
    public void onCreate(Application application) {
        global = Global.getInstance();

        Context context = application.getApplicationContext();
        global.setContext(context);

        printSdkInit(context);
        clearPrintFolder(context);
        clearPrintQueue(global.getPrintDevice());

        ConfigurationUtil configurationUtil = ConfigurationUtil.getInstance(context);
        global.setConfigurationUtil(configurationUtil);
    }

    @Override
    public void onSubProcessCreate(Application application) {

    }

    /**
     * 打印SDK初始化
     */
    private void printSdkInit(Context context) {
        File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        if (externalFilesDir == null) {
            // 外部存储不可用，使用内部存储
            externalFilesDir = context.getFilesDir();
            CLog.e("===> 外部存储不可用，使用内部存储");
        }
        String fileSavePath = externalFilesDir.getAbsolutePath();

        // 打印SDK初始化
        DeviceManager printDevice = DeviceManager.getInstance();
        boolean initResult = printDevice.init(context, fileSavePath);
        if (initResult) {
            global.setPrintDevice(printDevice);
            CLog.d("打印机SDK初始化成功");
        } else {
            CLog.d("打印机SDK初始化失败");
        }

    }

    /**
     * 清空打印缓存文件夹
     */
    private void clearPrintFolder(Context context) {
        FileUtil fileUtil = new FileUtil(context);
        fileUtil.clearFolder();
    }

    /**
     * 清空打印队列
     */
    private void clearPrintQueue(DeviceManager printDevice) {
        if (printDevice != null) {
            printDevice.clearPrintEnqueueFile();
        }
    }
}
